// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database({
	throwOnNotFound: false
})
const _ = db.command
function addPreZero(num, len = 2) {
	var t = (num + '').length,
		s = '';
	for (var i = 0; i < len - t; i++) {
		s += '0';
	}
	return s + num;
}
function getDate(date) {
	return date.getFullYear() + '-' + addPreZero(date.getMonth() + 1) + '-' + addPreZero(date.getDate())
}
function getDatetime(date) {
	return date.getFullYear() + '-' + addPreZero(date.getMonth() + 1) + '-' + addPreZero(date.getDate()) + ' ' + addPreZero(date.getHours()) + ':' + addPreZero(date.getMinutes()) + ':' + addPreZero(date.getSeconds())
}
// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	let product = await db.collection('product').doc(event._id).field({
		is_show: true,
		code_id: true,
		name: true,
		price: true,
		to_home: true,
		to_shop: true,
		shop_id: true
	}).skip(event.skip).limit(8).get()
	if (!product || !product.data || product.data.shop_id != event.shop_id) {
		return {
			msg: '未找到此产品',
			code: 20007
		}
	}

	console.log(product)
	//开始查找预约日期和时间
	var daily = await db.collection('daily').aggregate()
		.lookup({
			from: 'timeline',
			localField: '_id',
			foreignField: 'daily_id',
			as: 'times'
		}).match(
			{
				product_id:event._id,
				date:_.gte(getDate(new Date))
			},

		).end()
	return {
		code: 200,
		data: {
			product: product.data,
			daily: daily.list
		}
	}
}